package team.bluepen.supermarket.web.servlet;

import team.bluepen.supermarket.constant.Constant;
import team.bluepen.supermarket.constant.Error;
import team.bluepen.supermarket.data.hdfs.HdfsManager;
import team.bluepen.supermarket.util.FileUtil;
import team.bluepen.supermarket.web.base.BaseServlet;

import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * 文件上传
 * @author Kai
 */
@WebServlet(name = "FileUploadServlet", urlPatterns = "/api/file-upload")
@MultipartConfig(maxFileSize = Constant.FILE_MAX_SIZE)
public class FileUploadServlet extends BaseServlet {
    public static final String TEMP_DIRECTORY = "market_temp";


    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.sendRedirect("/");
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("utf-8");
        Part part = req.getPart("file_upload");
        String fileName = part.getSubmittedFileName();

        InputStream stream = part.getInputStream();
        if (stream.available() > Constant.FILE_MAX_SIZE) {
            resp.sendRedirect("/file.jsp?error=" + Error.ERROR_FILE_OVERSIZE.getValue());
            return;
        }

        String suffix = FileUtil.getFileNameSuffix(fileName);
        if (!suffix.equalsIgnoreCase("csv")
                && !suffix.equalsIgnoreCase("txt")) {
            resp.sendRedirect("/file.jsp?error=" + Error.ERROR_FILE_UNMATCHED.getValue());
            return;
        }

        String dateSuffix = getDateFormat();
        File outputFileDirectory = new File(TEMP_DIRECTORY);
        boolean dirState = outputFileDirectory.mkdirs();// 创建文件夹

        File file = new File(TEMP_DIRECTORY + "/" + fileName);

        if (!file.exists()) {
            boolean createState = file.createNewFile();
        }

        FileOutputStream outputStream = new FileOutputStream(file);

        int len;
        byte[] bytes = new byte[1024];
        while ((len = stream.read(bytes)) != -1) {
            outputStream.write(bytes, 0, len);
        }

        HdfsManager.getInstance().mkdirs(Constant.UPLOAD_DIRECTORY);
        Error uploadState = HdfsManager.getInstance().upload(file.getAbsolutePath(),
                Constant.UPLOAD_DIRECTORY + "/" + dateSuffix + "/" + fileName);
        boolean deleteState = file.delete();

        stream.close();
        outputStream.close();

        if (!uploadState.getState()) {
            resp.sendRedirect("/file.jsp?error=" + uploadState.getValue());
            return;
        }
        resp.sendRedirect("/file.jsp");
    }

    public static String getDateFormat() {
       return getDateFormat(System.currentTimeMillis());
    }

    public static String getDateFormat(long timestamp) {
        Date date = new Date(timestamp);
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy/MM");
        return dateFormat.format(date);
    }
}
